package de.hs_rm.mmk.group_talk.activities;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.UnknownHostException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

public class CreateGroup extends Activity {
	
	EditText groupname;
	Spinner speechDuration;
	String itemText;
	String nickname;
	String serverhost; 
	String serverport;
	String myport;
	Spinner speakDuration;
	ImageView speakDurationDisable;
	ImageButton done;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.create_group);
        
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);        
        
        speakDuration = (Spinner)findViewById(R.id.createGroup_speakDuration);
        speakDurationDisable = (ImageView)findViewById(R.id.createGroup_speakDurationDisable);
        
        //Get SharedPreferences
        final SharedPreferences preferences = Preferences.getPreferences(this);
        nickname = preferences.getString("nickname", ""); 
        serverhost = preferences.getString("serverhost", "");
        serverport = preferences.getString("serverport", "");
        myport = preferences.getString("myport", "");
        try {
        	InetAddress iadress = InetAddress.getByName(serverhost);
	        serverhost = iadress.getHostAddress();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
        // Get Views from XML
        groupname = (EditText)findViewById(R.id.createGroup_name);
        speechDuration = (Spinner)findViewById(R.id.createGroup_speakDuration);
        done = (ImageButton)findViewById(R.id.createGroup_doneBtn);
        
     // Initialize TextWatcher for grouname
        groupname.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				String text = groupname.getText().toString();
				if(text.trim().equals("")){
					done.setEnabled(false);
					Toast.makeText(getApplicationContext(), R.string.toast_noGroupName, Toast.LENGTH_SHORT).show();
				}else{
					done.setEnabled(true);
				}
				
			}
		});
        
        
        // Initialize Spinner for SpeakToken
        Spinner spToken = (Spinner) findViewById(R.id.createGroup_token);    
        ArrayAdapter adapter = ArrayAdapter.createFromResource(           
        		this, R.array.sp_groupConfigToken_array, android.R.layout.simple_spinner_item);    
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);    
        spToken.setAdapter(adapter);
        spToken.setOnItemSelectedListener(new OnItemSelectedListener() {
			
        	@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				Object item = parent.getItemAtPosition(pos);
				
				Resources res = getResources();
				String[] tokens = res.getStringArray(R.array.sp_groupConfigToken_array);
				if (item.toString().equals(tokens[0])){
					speakDuration.setVisibility(View.GONE);
					speakDurationDisable.setVisibility(View.VISIBLE);
				}else{
					speakDurationDisable.setVisibility(View.GONE);
					speakDuration.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {}
		});
        
        // Initialize Spinner for SpeakDuration 
        Spinner spDuration = (Spinner) findViewById(R.id.createGroup_speakDuration);    
        adapter = ArrayAdapter.createFromResource(           
        		this, R.array.sp_groupConfigDuration_array, android.R.layout.simple_spinner_item);    
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);    
        spDuration.setAdapter(adapter);
        spDuration.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				Object item = parent.getItemAtPosition(pos);
				itemText = item.toString();				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {}
			
		});
    }
	
	@Override
	public void onStart(){
		super.onStart();
		EditText groupname = (EditText)findViewById(R.id.createGroup_name);
		if(groupname.getText().toString().trim().length() == 0){
			ImageButton doneBtn = (ImageButton)findViewById(R.id.createGroup_doneBtn);
			doneBtn.setEnabled(false);
			Toast.makeText(getApplicationContext(), R.string.toast_noGroupName, Toast.LENGTH_LONG).show();
		}
	}
	
	public void openTalkmasterActivity(final View view) {
		
		Communication comm = Communication.getInstance(serverhost, new Integer(myport).intValue(), new Integer(serverport).intValue());		
		comm.createNewGroup(groupname.getText().toString(), nickname);		
		
		int ok = comm.waitingForResponse();
			
		if(ok == 0) {
			
			comm.setSpeechState(true);
			
			Intent intent = new Intent(getApplicationContext(),  TalkmasterView.class);
			intent.putExtra("Groupname", String.valueOf(groupname.getText()));
			intent.putExtra("SpeechDuration", itemText);
			//Log.d("TAG",String.valueOf(itemText));
			startActivity(intent);
			
			
		}
		
		else if(ok == 1) {
			
			Toast.makeText(getApplicationContext(), "Group already exists", Toast.LENGTH_SHORT).show();
			
		}
		
		else {
			
			AlertDialog alertDialog = new AlertDialog.Builder(this).create();
			alertDialog.setTitle("Create New Group Request");
			alertDialog.setMessage("Timeout, Server unavailable");
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			   public void onClick(DialogInterface dialog, int which) {
			      // here you can add functions
			   }
			});
			alertDialog.setIcon(R.drawable.icon);
			alertDialog.show();
		}
			
		
		
	}
}
